﻿/// <reference path="../../js/utils.js" />
'use strict';

define([
    'screenView',
    'commonModels',

    'backgrid.all',

    'backbone.modelbinder',
],
function (
    ScreenView,
    CommonModels,
    Backgrid
) {
    var View = ScreenView.extend({
        super: null,

        name: 'customers',
        title: 'Clientes',

        catalogCollFn: CommonModels.CustomerColl,
        catalogColl: null,
        catalogCollFiltered: null,
        catalogDefault: null,
        catalogGrid: null,
        catalogModelFn: CommonModels.CustomerModel,
        catalogName: 'Customer',

        constructor: function () {
            this.super = View.__super__;

            this.catalogColl = new this.catalogCollFn(
                //null,
                //{
                //    mode: 'client',
                //    state: {
                //        pageSize: 10,
                //    },
                //}
            );
            this.catalogCollFiltered = new this.catalogCollFn();

            this.catalogDefault = new this.catalogModelFn();

            this.modelBinder = new Backbone.ModelBinder();

            return this.super.constructor.apply(this, arguments);
        },

        applyFilters: function () {
            var newCollItems = [],
                cityQuery = new RegExp(this.model.get('city').trim().split(/\s+/).join('|'), 'i'),
                searchQuery = new RegExp(this.model.get('search').trim().split(/\s+/).join('|'), 'i');

            this.catalogColl.each(function (model) {
                var attrs = model.toJSON();

                if (cityQuery.test(attrs.city + ''))
                {
                    for (var attrName in attrs) {
                        if (searchQuery.test(attrs[attrName] + '')) {
                            newCollItems.push(model);
                            break;
                        }
                    }
                }
            });


            //Add empty model to add new row.
            newCollItems.push(new this.catalogModelFn());


            this.catalogCollFiltered.reset(newCollItems);
        },
        delegateModelEvents: function () {
            this.listenTo(this.model, 'change', this._model_changed, this)
                .listenTo(this.catalogCollFiltered, 'add', this._catalogCollFiltered_add, this)
                .listenTo(this.catalogCollFiltered, 'change', this._catalogCollFiltered_change, this);

            return this.super.delegateModelEvents.apply(this, arguments);
        },
        render: function () {
            this.super.render.apply(this);

            var that = this;

            /* First render actions. */
            if (!this.rendered) {
                this.catalogGrid = new Backgrid.Grid({
                    columns: [
                        {
                            name: 'code',
                            label: 'Código',
                            cell: Backgrid.Extension.StringCenterCell.extend({
                                formatter: _.extend({},  Backgrid.Extension.PadCellFormatter.prototype, {
                                    pad: '0000',
                                }),
                            }),
                        },
                        {
                            name: 'name',
                            label: 'Nombre',
                            cell: 'string-center',
                        },
                        {
                            name: 'description',
                            label: 'Descripción',
                            cell: 'string-left',
                        },
                        {
                            name: 'address',
                            label: 'Dirección',
                            cell: 'string-left',
                        },
                        {
                            name: 'city',
                            label: 'Ciudad/Barrio',
                            cell: 'string-left',
                        },
                        {
                            name: 'cuit',
                            label: 'Cuit/Cuil',
                            cell: 'string-center',
                        },
                        {
                            name: 'contact',
                            label: 'Contacto',
                            cell: 'string-left',
                        },
                        {
                            name: 'telephone',
                            label: 'Teléfono',
                            cell: 'string-left',
                        },
                        {
                            name: 'email',
                            label: 'E-Mail',
                            cell: 'string-left',
                        },
                        {
                            name: 'important',
                            label: 'Importante',
                            cell: 'boolean',
                        },
                        {
                            name: 'active',
                            label: 'Activo',
                            cell: 'boolean',
                        },
                    ],
                    collection: this.catalogCollFiltered,
                });
                this.catalogGrid.render();
                // Render the grid and attach the Grid's root to your HTML document
                this.$el.find('#catalog').append(this.catalogGrid.el);


                $('.clearable').clearSearch();


                //var paginator = new Backgrid.Extension.Paginator({

                //    //// If you anticipate a large number of pages, you can adjust
                //    //// the number of page handles to show. The sliding window
                //    //// will automatically show the next set of page handles when
                //    //// you click next at the end of a window.
                //    //windowSize: 20, // Default is 10

                //    //// Used to multiple windowSize to yield a number of pages to slide,
                //    //// in the case the number is 5
                //    //slideScale: 0.25, // Default is 0.5

                //    //// Whether sorting should go back to the first page
                //    //goBackFirstOnSort: false, // Default is true

                //    collection: this.catalogColl,
                //});

                //gridContainer.append(paginator.render().el);



                this.modelBinder.bind(
                    this.model,
                    this.el,
                    null,
                    {
                        changeTriggers: {
                            '': 'change',
                            '.clearable': 'keyup',
                        },
                    }
                );


                /* Indicates that the view was rendered at least one time. */
                this.rendered = true;
            }
            /* Not first render actions. */
            else {
                
            }


            return this;
        },
        show: function (data) {
            this.catalogColl.fetch({ success: _.bind(this._catalogColl_fetch_success, this) });

            return this.super.show.apply(this, arguments);
        },

        _catalogCollFiltered_add: function (model, coll, options) {
            try {
                this.applyFilters();
            }
            catch (Error) { console.error(Error); }
        },
        _catalogCollFiltered_change: function (model, coll, options) {
            try {
                var id = model.get('id');

                if (id != 0) {
                    App.billingService.updateCatalogItem(
                        {
                            CatalogName: this.catalogName,
                            Keys: {
                                Id: model.get('id'),
                            },
                            Properties: model.changed,
                        },
                        {
                            success: function (resp) {
                                if (resp.Success == true) {
                                    console.debug(resp);
                                }
                            },
                            error: function () {
                                console.debug('error');
                            },
                        }
                    );
                }
                else {
                    this.catalogColl.add(model);

                    App.billingService.addCatalogItem(
                        {
                            CatalogName: this.catalogName,
                            Properties: model.changed,
                        },
                        {
                            success: function (resp) {
                                if (resp.Success == true) {
                                    //Set model id.
                                    model.set({ id: resp.Data, }, { silent: true, });
                                }
                            },
                            error: function () {
                                console.debug('error');
                            },
                        }
                    );
                }


                this.applyFilters();
            }
            catch (Error) { console.error(Error); }
        },
        _catalogColl_fetch_success: function (coll) {
            try {
                this.applyFilters();
            }
            catch (Error) { console.error(Error); }
        },
        _model_changed: function (model, options) {
            try {
                this.applyFilters();
            }
            catch (Error) { console.error(Error); }
        },
    });

    return View;
});